<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名">
                <a-input v-model="queryParam.username" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option value="0">正常</a-select-option>
                  <a-select-option value="1">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <!-- <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>

            <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown> -->
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text, record">
          <a-switch :default-checked="text === 0" @change="onChangeSwitch(record)" />
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEditPassword(record)">修改密码</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk"
      />

      <change-password-form
        ref="changePasswordModal"
        :visible="passwordVisible"
        :loading="passwordConfirmLoading"
        :id="id"
        @cancel="passwordHandleCancel"
        @ok="passwordHandleOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { query, add, editStatus, del, changePassword } from '@/api/admin'
import ChangePasswordForm from './components/ChangePasswordForm'
import CreateForm from './components/CreateForm'

const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    scopedSlots: { customRender: 'create_time' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]
const statusMap = {
  1: {
    status: 'default',
    text: '禁用'
  },
  0: {
    status: 'success',
    text: '正常'
  }
}
export default {
  name: 'Admin',
  components: {
    STable,
    CreateForm,
    ChangePasswordForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return query(requestParameters).then(res => {
          console.log(res)
          return res.result
        }).catch(errors => {
          console.log(errors)
        })
      },
      passwordVisible: false,
      passwordConfirmLoading: false,
      id: 0
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
  },
  computed: {

  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    // handleEdit (record) {
    //   this.visible = true
    //   this.mdl = { ...record }
    // },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          add(values).then(res => {
            console.log(res)
            this.visible = false
            this.confirmLoading = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.$message.success('新增成功')
          }).catch(errors => {
            console.log(errors)
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 修改状态
    onChangeSwitch (data) {
      editStatus({ id: data.id })
    },
    // 修改密码
    handleEditPassword (record) {
      this.passwordVisible = true
      this.id = record.id
    },
    // 修改密码取消
    passwordHandleCancel () {
      this.passwordVisible = false
      const form = this.$refs.changePasswordModal.form
      form.resetFields()
    },
    // 修改密码确认
    passwordHandleOk () {
      const form = this.$refs.changePasswordModal.form
      this.passwordConfirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          // 新增
          changePassword(values).then(res => {
            if (res.code === 1) {
              this.$message.error(res.message)
              return
            }
            this.passwordVisible = false
            // 重置表单数据
            form.resetFields()
            this.$message.success('密码修改成功')
            this.id = 0
          }).catch(errors => {
            console.log(errors)
          }).finally(() => {
            this.passwordConfirmLoading = false
          })
        } else {
          this.passwordConfirmLoading = false
        }
      })
    },
    handleDel (record) {
      console.log(record)
      const _that = this
      this.$confirm({
        title: '请确认要删除账号？',
        content: h => <div style="color:red;">正在删除“{ record.username }”</div>,
        icon: h => <a-icon style="color:red;" type="delete" />,
        onOk () {
          del({ id: record.id }).then(res => {
            console.log(res)
            _that.$message.success('删除成功')
            // 刷新表格
            _that.$refs.table.refresh()
          }).catch(errors => {
            console.log(errors)
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    }
  }
}
</script>
